package com.bluedot.www.baiyetest.servlet.baiyetest.service;

import com.bluedot.www.baiyetest.servlet.baiyetest.pojo.User;
import com.bluedot.www.baiyetest.servlet.baiyetest.utils.Util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @author baiye
 * @date 2021/08/04/19:58
 * @Description
 */
public class ServiceContext {
    // 记录子类 service url 路径对应 class 全类名
    private static Map<String, String> serviceMap;
    // url映射class类名 文件名
    private static final String SERVICE_PROPERTIES = "service.properties";


    public ServiceContext() throws IOException {
        // 1. 如果 serviceMap 为空
        if (serviceMap == null) {
            serviceMap = new HashMap<>(16);
            // 2. 读取配置文件并加载到 map 中
            InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(SERVICE_PROPERTIES);
            Properties properties = Util.loadProperties(resourceAsStream);
            Set<String> services = properties.stringPropertyNames();
            for (String key : services) {
                serviceMap.put(key, (String) properties.get(key));
            }
        }
    }

    public User execute(String serviceName, String methodName, String parameter) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        String allName = serviceMap.get(serviceName);
        Class clazz = Class.forName(allName);
        Object object = clazz.newInstance();
        Method method = clazz.getDeclaredMethod(methodName, String.class);
        method.setAccessible(true);
        User result = (User)method.invoke(object, parameter);
        System.out.println("result="+result);
        return result;
    }
}
